<template>
  <div class="charts-wrapper">
    <div v-for="(item, index) in factors" :key="item" class="charts-item">
      <div :ref="el => setDivRef(el, index)" style="width: 400px; height: 300px" />
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import { http } from "@/utils/http";
import * as echarts from "echarts";
const chartsRef = ref(null);

type ResultTable = {
  total?: number;
  data?: Array<any>;
};

const props = defineProps({
  factors: {
    type: Array,
    default: () => []
  }
});
watch(
  () => props.factors,
  (newValue, oldValue) => {
    if (newValue != null && newValue.length > 0) {
      getList();
    }
  }
);

const getList = () => {
  // let params = {
  //   //factorList: ["ACM_F", "Humidity", "FFU_Speed", "Temperature", "AMC_VOC_Ratio", "VOC_VOC7", "AMC_NH3", "AMC_SO4"]
  //   factorList: props.factors
  // };
  // queryList(params).then(res => {
  //   //测试数据
  //   createChart(res);
  // });
  // let params = {
  //   //factorList: ["ACM_F", "Humidity", "FFU_Speed", "Temperature", "AMC_VOC_Ratio", "VOC_VOC7", "AMC_NH3", "AMC_SO4"]
  //   factorList: props.factors
  // };
  queryList({}).then(res => {
    //测试数据
    createChart(res);
  });
};

//查询SPC指标列表
const queryList = (data?: object) => {
  return http.request<ResultTable>("post", `/operation/api/v1/machine/correlationFactors/queryCorrelationFactorSAndResult`, {
    data
  });
};
const divRefs = ref([]);
const setDivRef = (el, index) => {
  if (el) {
    divRefs.value[index] = el;
  }
};
const createChart = res => {
  let resKeyAry = Object.keys(res);
  // props.factors.forEach((value: string, index) => {
  //   const chart = echarts.init(chartsRef.value[index]);
  //   let resKey = resKeyAry[index];
  //   let option = getOption(resKey, res[resKey]);
  //   chart.setOption(option);
  // });
  resKeyAry.forEach((item, index) => {
    const chart = echarts.init(divRefs.value[index]);
    let resKey = resKeyAry[index];
    let option = getOption(resKey, res[resKey]);
    chart.setOption(option);
  });
};
/**
 * @desc: 获取echart数据选项
 * @return: {*}
 * @param {*} title 图表key
 * @param {*} obj 图表数据
 */
const getOption = (title, obj) => {
  const option = {
    title: {
      show: true,
      text: title,
      textAlign: "left"
    },
    xAxis: {},
    yAxis: {},
    series: [
      {
        symbolSize: 10,
        type: "scatter",
        data: []
      }
    ]
  };
  let data = [];
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      obj[key].forEach(val => {
        data.push([Number.parseFloat(key), val]);
      });
    }
  }
  option.series[0].data = data;
  return option;
};
</script>
<style lang="scss" scoped>
.charts-wrapper {
  display: flex;
  flex-wrap: wrap;
}
</style>
